import React, { useState, useEffect } from 'react';
import SearchList from '@/components/SearchList';
import { Table, Button, notification, Tooltip } from 'antd';
import {
  PlusCircleFilled,
  EyeFilled,
  EditFilled,
  DeleteFilled,
  SnippetsFilled,
} from '@ant-design/icons';
import { transFormIndex, showDeleteConfirm } from '@/utils/util';
import API from '@/api/cyindex.js';
import { useModel } from 'umi';

// 安全事件通报
const safetyIncidentNotice = ({ history }) => {
  const { initialState } = useModel('@@initialState');
  const { userId, orgId } = initialState.info;
  const state = { 1: '已通报', 0: '草稿' };
  const [isshow, setIsshow] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [AQSJTB_SJLX, setAQSJTB_SJLX] = useState(null);
  const [SJLY, setSJLY] = useState(null);
  const [JJCD, setJJCD] = useState(null);
  const _JJCD = {};
  const _SJLY = {};
  const _AQSJTB_SJLX = {};
  const JJCDList = [];
  const SJLYList = [];
  const AQSJTB_SJLXList = [];
  const receiverList = {};
  const [pagination, setPagination] = useState({
    pageSize: 10, //每条的页数
    current: 1,
    showQuickJumper: true,
  });
  //查询参数
  const [params, setParams] = useState({
    eventSource: '-1',
    eventType: '-1',
    emergency: '-1',
    notificationTime: '',
  });
  const searchList = [
    {
      name: 'eventSource',
      title: '事件来源',
      type: 'select',
      otherProps: {
        options: SJLY,
      },
    },
    {
      name: 'eventType',
      title: '事件类型',
      type: 'select',
      otherProps: {
        options: AQSJTB_SJLX,
      },
    },
    {
      name: 'emergency',
      title: '紧急程度',
      type: 'select',
      otherProps: {
        options: JJCD,
      },
    },
    {
      name: 'notificationTime',
      title: '通报时间',
      type: 'datepicker',
    },
  ];
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      render: (text, r, index) => transFormIndex(pagination, index),
    },
    {
      title: '通报函号',
      dataIndex: 'reportId',
      align: 'center',
    },
    {
      title: '事件来源',
      dataIndex: 'eventSource',
      ellipsis: true,
      align: 'center',
    },
    {
      title: '事件类型',
      dataIndex: 'eventType',
      align: 'center',
    },
    {
      title: '紧急程度',
      dataIndex: 'emergency',
      align: 'center',
    },
    {
      title: '接收单位',
      dataIndex: 'receiverName',
      ellipsis: true,
      align: 'center',
    },
    {
      title: '通报时间',
      dataIndex: 'notificationTime',
      ellipsis: true,
      align: 'center',
    },
    {
      title: '通报状态',
      dataIndex: '_reportState',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'Operation',
      align: 'center',
      render: (text, r) => (
        <div>
          <Tooltip title="查看">
            <Button
              type="link"
              icon={<EyeFilled />}
              className="table-icon"
              onClick={checkLink.bind(null, r)}
            ></Button>
          </Tooltip>
          {(r.userId == userId && r.reportState == 0) ||
          (r.disposeState == 0 && orgId != '101') ? (
            <Tooltip title={orgId == '101' ? '编辑' : '处置'}>
              <Button
                type="link"
                icon={orgId == '101' ? <EditFilled /> : <SnippetsFilled />}
                className="table-icon"
                onClick={editLink.bind(null, r)}
              ></Button>
            </Tooltip>
          ) : (
            ''
          )}
          {isshow && r.reportState == '0' && r.userId == userId ? (
            <Tooltip title="删除">
              <Button
                type="link"
                icon={<DeleteFilled />}
                className="table-icon"
                onClick={() => showDeleteConfirm(() => delFn(r.id))}
              ></Button>
            </Tooltip>
          ) : (
            ''
          )}
        </div>
      ),
    },
  ];
  const createLink = () => {
    history.push('/networkInfor/safetyIncidentNotice/create');
  };
  const checkLink = (r) => {
    if (isshow) {
      r = JSON.stringify(r);
      history.push({
        pathname: '/networkInfor/safetyIncidentNotice/check',
        query: { r },
      });
    } else {
      r.tid = r.id;
      r.receiverId = initialState.info.orgId;
      const xx = JSON.stringify(r);
      history.push({
        // 单位跳转查看
        pathname: '/networkInfor/safetyIncidentNotice/unit_check',
        query: { xx },
      });
    }
  };
  const editLink = (r) => {
    r = JSON.stringify(r);
    history.push({
      // 交通厅跳转编辑
      pathname: `/networkInfor/safetyIncidentNotice/${
        isshow ? 'edit' : 'unit_edit'
      }`,
      query: { r },
    });
  };
  const pageSizeChange = (page) => {
    initList({
      ...params,
      pageNo: page.current,
      pageSize: page.pageSize,
      showQuickJumper: true,
    });
    setParams({
      ...params,
      pageNo: page.current,
      pageSize: page.pageSize,
    });
  };
  const changeParams = (data) => {
    setParams({
      ...data,
      pageSize: 10,
      pageNo: 1,
    });
  };

  const delFn = (id) => {
    API.delNotification({ id: id }).then((res) => {
      if (res) {
        notification.success({
          message: '删除成功',
        });
        initList(params);
      }
    });
  };

  function initList(params = {}) {
    const dd = {
      eventSource: '-1',
      eventType: '-1',
      emergency: '-1',
      notificationTime: '',
    };
    for (let p in dd) {
      //参数为空时设置为-1
      if (params[p] == undefined) {
        params[p] = dd[p];
      }
    }
    if (params && params.notificationTime) {
      //修改时间参数的格式
      params.notificationTime = params.notificationTime.format('YYYY-MM-DD');
    }
    //交通厅=2， 新增,查看,编辑,删除
    //单位，查看，处置
    const roleId = initialState.info.userRoleId;
    if (roleId == 2) {
      //交通厅的角色为2
      setIsshow(true);
    }
    API.showServiceProviderList().then((res) => {
      if (res) {
        res.t.map((item) => {
          //接收单位
          receiverList[item.id] = item.name;
        });
      }
    });
    API.dictItemList() //字典
      .then((res) => {
        if (res) {
          res.t.map((item) => {
            if (item.dictCode == 'JJCD') {
              _JJCD[item.dictItemType] = item.dictItemName; //表格里返回数据值的修改
              JJCDList.push({
                //下拉框
                label: item.dictItemName,
                value: item.dictItemType,
              });
            }
            if (item.dictCode == 'SJLY') {
              _SJLY[item.dictItemType] = item.dictItemName;
              SJLYList.push({
                label: item.dictItemName,
                value: item.dictItemType,
              });
            }
            if (item.dictCode == 'AQSJTB_SJLX') {
              _AQSJTB_SJLX[item.dictItemType] = item.dictItemName;
              AQSJTB_SJLXList.push({
                label: item.dictItemName,
                value: item.dictItemType,
              });
            }
          });
          setJJCD(JJCDList);
          setSJLY(SJLYList);
          setAQSJTB_SJLX(AQSJTB_SJLXList);
        }
      })
      .then(() => {
        getNotificationList(params);
      });
  }
  const getNotificationList = (params) => {
    API.getNotificationList(params).then((res) => {
      if (res) {
        setDataSource(
          res.t.queryList.map((item) => ({
            //表格初始数据
            ...item,
            rId: item.receiverId,
            eventSource: _SJLY[item.eventSource],
            eventType: _AQSJTB_SJLX[item.eventType],
            emergency: _JJCD[item.emergency],
            _reportState: state[item.reportState],
            reportState: item.reportState,
          })),
        );
        setPagination({
          showQuickJumper: true,
          current: res.t.currentPage,
          pageSize: res.t.pageSize,
          total: res.t.totalSize,
        });
      }
    });
  };
  useEffect(() => {
    initList(params);
  }, [params]);
  return (
    <>
      <SearchList searchList={searchList} initList={changeParams}></SearchList>
      <div className="main-x bgf">
        {isshow ? (
          <div className="tools-x">
            <Button
              type="link"
              icon={<PlusCircleFilled />}
              className="btn-icon"
              onClick={createLink}
            >
              新增
            </Button>
          </div>
        ) : (
          ''
        )}
        <Table
          columns={columns}
          dataSource={dataSource}
          rowKey="id"
          pagination={pagination}
          className={isshow ? 'custom-table mt20' : 'custom-table'}
          onChange={pageSizeChange}
        ></Table>
      </div>
    </>
  );
};

export default safetyIncidentNotice;
